import uuid
from uuid import UUID

from fastapi.security import OAuth2PasswordRequestForm
from jose.constants import Algorithms
from pydantic import BaseModel
from rich import print

from domain.authentication import UserInDB

# to get a string like this run:
# openssl rand -hex 32
SECRET_KEY = "04d9da230a24f78c5efa65b397aa90b14fd0a0e9d2fa40a9c27416834328da57"
ACCESS_TOKEN_EXPIRE_MINUTES = 30


class JwtEncryption(Algorithms):
    pass


def fake_connect_db(uri: str):
    with open(uri, 'r+') as file:
        import json
        db = json.load(file)
    return db


def get_local_datetime():
    from datetime import datetime as dt, timedelta
    return dt.utcnow() + timedelta(hours=8)


def get_user(a_uuid: UUID):
    db = fake_connect_db('db/db.json')
    user_uuid = a_uuid.hex
    if user_uuid in db:
        user_dict = db[user_uuid]
        return UserInDB(**user_dict)


class OAuthForm(BaseModel):
    uuid: UUID
    name: str
    email: str
    password: str
    scopes: list[str]
    client_id: str | None = None
    client_secret: str | None = None


def get_custom_oauth_form(form_data: OAuth2PasswordRequestForm):
    username, password = (form_data.username, form_data.password)
    name, email = form_data.username.split(":")
    user_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, username)  # username format - "name:email"

    return OAuthForm(
        uuid=user_uuid,
        name=name,
        email=email,
        password=password,
        scopes=form_data.scopes,
        client_id=form_data.client_id,
        client_secret=form_data.client_secret
    )


def print_oauth_form(my_oauth_form: OAuthForm):
    print(f"""
    ===================================\n
    Form data\n
    - name: {my_oauth_form.name},\n
    - email: {my_oauth_form.email},\n
    - scopes: {my_oauth_form.scopes},\n
    - client_id: {my_oauth_form.client_id},\n
    - client_secret: {my_oauth_form.client_secret}\n
    ===================================
    """.strip())
